package cn.wp.user.controller;

import cn.wp.basic.util.AjaxResult;
import cn.wp.user.constant.WechatConstant;
import cn.wp.user.dto.UserDto;
import cn.wp.user.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * 第三方登录接口
 */
@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private IWechatService wechatService;

    /**
     * 跳转到微信登录页面（拉去二维码）
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "redirect:"+ WechatConstant.LOGIN_URL.replace("APPID", WechatConstant.APPID)
                .replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
    }

    /**
     * 回调接口，扫完二维码调用
     * @param code
     * @return
     */
    @RequestMapping("/callback")
    public String callback(String code){
        return "redirect:http://localhost:8082/callback.html?code="+code;
    }

    /**
     * 处理回调方法
     * @param map
     * @return
     */
    @PostMapping("/handleCallBackMethod")
    @ResponseBody
    public AjaxResult handleCallBackMethod(@RequestBody Map<String,String> map){
        try {
            Map<String,Object> resultMap = wechatService.handleCallBackMethod(map);
            return AjaxResult.me().setResultObject(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
    }

    /**
     * 绑定手机号码
     * @param userDto
     * @return
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody UserDto userDto){
        try {
            Map<String, Object> resultMap = wechatService.binder(userDto);
            return AjaxResult.me().setResultObject(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
    }
}
